package com.mh.mh.netty;

import com.mh.mh.netty.handler.HandlerServerHello;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

/**
 * 服务端启动类
 */
public class AppServerHello {
    private final int port ;

    public AppServerHello(int port){
        this.port = port;
    }


    public void run() throws InterruptedException {
        /**
         * 配置相应的参数，提供连结到远端的方法
         * // IO线程池
         */
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            // 客户端辅助启动类
            ServerBootstrap bs = new ServerBootstrap();
            bs.group(group)
                    // 实例化一个channel
                    .channel(NioServerSocketChannel.class)
                    // 设置监听端口
                    .localAddress(new InetSocketAddress(port))
                    // 进行通道初始化配置
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            // pipeline 是所有handler的容器，会一步步去执行handler
                            socketChannel.pipeline().addLast(new HandlerServerHello());// 添加自定义的handler
                        }
                    });

            // 连接到远程节点，等待连接完成
            ChannelFuture future = bs.bind().sync();
            System.out.println("在"+future.channel().localAddress()+"上开启监听");
            // 阻塞操作，closeFuture开启了一个channel的监听（这期间channel在进行各种操作），直到链路断开
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new AppServerHello( 7770).run();
    }


}
